package com.hejing.网络编程概述;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ClassName: InetAddressTest
 * Package: com.hejing.网络编程概述
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-06-02 18:16
 * @Version: 1.0
 */
public class InetAddressTest {
    public static void main(String[] args) {
        // 1、实例化

        try {
            // getByName(String host): 获取指定ip对应的InetAddress的实例。
            InetAddress inet1 = InetAddress.getByName("192.168.23.12");
            System.out.println(inet1);  // /192.168.23.12

            InetAddress inet2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inet2);  // www.baidu.com/110.242.68.4

            // getLocalHost(): 获取本地ip对应的InetAddress的实例
            InetAddress inet3 = InetAddress.getLocalHost();
            System.out.println(inet3);  // LAPTOP-8M26RBI4/192.168.179.1

            InetAddress inet4 = InetAddress.getByName("127.0.0.1");  // /127.0.0.1
            System.out.println(inet4);

            // 两个常用的方法:
            System.out.println(inet1.getHostName());  // 没有域名则返回ip地址: 192.168.23.12
            System.out.println(inet1.getHostAddress());  // 192.168.23.12

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }
}























